<?php

class AuthController extends Controller
{
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
	public function actionIndex()
	{
		if(Yii::app()->user->isGuest)
			$this->redirect($this->createUrl('auth/signin'));
		else
			$this->redirect($this->createUrl('field/'));
	}
	
	public function actionSignin()
	{
		
		if(!Yii::app()->user->isGuest)
			$this->redirect($this->createUrl('field/'));
		
		$model=new User;
		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			if($model->login()){
				$this->redirect($this->createUrl('field/'));
			}
		}
			
		$this->render('signin', array('model' => $model));
	}
	
	public function actionSignup()
	{
		
		if(!Yii::app()->user->isGuest)
			$this->redirect($this->createUrl('field/'));
		
		$model = new User;
		
		if(isset($_POST['ajax']) && $_POST['ajax']==='registration-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		
		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			$model->verifyCode = $_POST['User']['verifyCode'];
			$model->passwordRe = $_POST['User']['passwordRe'];
			$model->password = $model->hashPassword($model->password);
			$model->passwordRe = $model->hashPassword($model->passwordRe);
			if($model->validate())
			{
			
				$user = new User;
				$user->login = $model->login; 
				$user->password = $model->password;
				$user->email = $model->email;
				$user->current_settlement = 0;
				$user->insert();				
			
				$users = User::model()->findAll();
				$id_user = $users[count($users) - 1]->id;
			
				User::createSettlement($id_user);
				
				$this->redirect($this->createUrl('auth/signin'));
			}
		}
		$this->render('signup', array('model' => $model));
	}
	
	

	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

	public function actionLogin()
	{
		$model=new LoginForm;
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		$this->render('login',array('model'=>$model));
	}
	
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
}